import { Component, ViewChild } from '@angular/core';
import { environment } from 'src/environments/environment';
import { OutInspectionDetailsComponent } from '../out-inspection/out-inspection-details/out-inspection-details.component';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { LogComponent } from 'src/app/@shared/components/log/log.component';
import {
  DataTableComponent,
  DialogService,
  DrawerService,
  IDrawerOpenResult,
  TableWidthConfig,
} from '@devui';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';

import { ProductionInspectionOrder } from 'src/app/@core/data/job';
import { JobOrderService } from 'src/app/@core/services/jobOrder/job-order.service';
import { ProductInspectionDetailsComponent } from './product-inspection-details/product-inspection-details.component';
import { Router } from '@angular/router';
import { SelectJobOrderProcessComponent } from '../../purchase/purchaseOut/select-job-order-process/select-job-order-process.component';

@Component({
  selector: 'app-product-inspection',
  templateUrl: './product-inspection.component.html',
  styleUrls: ['./product-inspection.component.scss'],
})
export class ProductInspectionComponent {
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20,
  };
  results: IDrawerOpenResult;
  pageSizeOptions = [10, 20, 30, 50, 100];
  tableData: ProductionInspectionOrder[] = [
    {
      productionInspectionOrderId: 0,
      productionInspectionOrderNum: '',
      jobOrderProcessId: 0,
      jobNum: '',
      inspectionType: '',
      productNum: '',
      productName: '',
      partType: '',
      momVersion: '',
      uom: '',
      pendingInspectionQuantity: 0,
      inspectionStatus: '',
      qualifiedAmount: 0,
      unqualifiedAmount: 0,
      scrapAmount: 0,
      inspectionProjects: [],
      remarks: '',
      attachments: [],
      processNum: '',
      procssName: ''
    },
  ];
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '操作',
        fieldType: 'text',
        fixedLeft: '80px',
      },
      {
        field: 'name',
        header: '生产质检单号',
        fieldType: 'text',
        fixedLeft: '350px',
      },
      {
        field: '单据类型',
        header: '单据类型',
        fieldType: 'text',
      },
      {
        field: '检验状态',
        header: '检验状态',
        fieldType: 'text',
      },
      {
        field: '物料编码',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: '物料名称',
        header: '物料名称',
        fieldType: 'text',
      },
      {
        field: '规格型号',
        header: '规格型号',
        fieldType: 'text',
      },
      {
        field: '物料单位',
        header: '物料单位',
        fieldType: 'text',
      },
      {
        field: '检验数量',
        header: '检验数量',
        fieldType: 'text',
      },
      {
        field: '合格数量',
        header: '合格数量',
        fieldType: 'text',
      },
      {
        field: '不合格数量',
        header: '不合格数量',
        fieldType: 'text',
      },
      {
        field: '报废数量',
        header: '报废数量',
        fieldType: 'text',
      },
      {
        field: '工单号',
        header: '工单号',
        fieldType: 'text',
      },
      {
        field: '检验日期',
        header: '检验日期',
        fieldType: 'text',
      },
      {
        field: '二维码',
        header: '二维码',
        fieldType: 'text',
      },
      {
        field: '备注',
        header: '备注',
        fieldType: 'text',
      },
    ],
  }; //表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px',
    },
    {
      field: '操作',
      width: '270px',
    },
    {
      field: '生产质检单',
      width: '200px',
    },
    {
      field: '物料名称',
      width: '150px',
    },
    {
      field: '物料名称',
      width: '150px',
    },
    {
      field: '物料编码',
      width: '150px',
    },

    {
      field: '规格型号',
      width: '150px',
    },
    {
      field: '物料描述',
      width: '150px',
    },
    {
      field: '物料单位',
      width: '150px',
    },

    {
      field: '检验数量',
      width: '150px',
    },
    {
      field: '合格数量',
      width: '150px',
    },
    {
      field: '不合格数量',
      width: '150px',
    },
    {
      field: '仓库名称',
      width: '150px',
    },
    {
      field: '工单号',
      width: '200px',
    },
    {
      field: '二维码',
      width: '200px',
    },
    {
      field: '备注',
      width: '150px',
    },
  ]; //表格宽度配置
  msgs: { severity: any; summary: any; content: any }[];
  fifter = {
    PageSize: 20,
    PageNumber: 1,
    InspectionNum: '',
    JobOrderNum: '',
    ProductNum: '',
    Inspector: '',
  };
  customer: any = [];
  creatTime: any = [];
  splitBarSize = '0px';
  partDetailHeight = '100%';
  @ViewChild(DataTableComponent, { static: true })
  datatable: DataTableComponent;
  checkedIds: any = [];
  partDetail: any = [];
  selectedRowIndex: any;
  date = [];
  employeeCode=""
  // statusOptions = ['未开始审核', '审核中', '审核通过'];
  constructor(
    private SharedMethodService: SharedMethodService,
    private DialogService: DialogService,
    private dialogService: DialogService,
    private JobOrderService: JobOrderService,
    private router:Router
  ){}
  ngOnInit(): void {
    this.filter();
    const userInfoString = JSON.parse(localStorage.getItem('userinfo'));
    this.employeeCode=userInfoString.employeeCode;
  }
  filter() {
    this.JobOrderService.GetPagedProductionInspectionOrder(this.fifter).subscribe(
      (data: any) => {
        this.tableData = data.items;
        this.pager.total = data.totalCount;
      },
      (error: any) => {
        this.showToast('error', '失败', error.error || '服务器连接失败');
      }
    );
  }
  filter2() {
    this.fifter.PageNumber = 1;
    this.JobOrderService.GetPagedProductionInspectionOrder(this.fifter).subscribe(
      (data: any) => {
        this.tableData = data.items;
        this.pager.total = data.totalCount;
      },
      (error: any) => {
        this.showToast('error', '失败', error.error || '服务器连接失败');
      }
    );
  }
  reset() {
    this.fifter = {
      PageSize: 20,
      PageNumber: 1,
      InspectionNum: '',
      JobOrderNum: '',
      ProductNum: '',
      Inspector: '',
    };
    this.date = [];
    this.filter();
  }
  onRowCheckChange(
    checked: any,
    rowIndex: any,
    nestedIndex: any,
    rowItem: { $checked: any; $halfChecked: boolean }
  ) {
    this.SharedMethodService.onRowCheckChange(
      checked,
      rowIndex,
      nestedIndex,
      rowItem,
      this.datatable
    );
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'purchaseArrivalOrderId'
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'purchaseArrivalOrderNum'
    ).subscribe((data: any) => {
      this.checkedCodes = data;
    });
  } //获取选中行
  CheckedRows = [];
  getCheckedRowsData() {
    this.SharedMethodService.getCheckedRowsData(this.datatable).subscribe(
      (data: any) => {
        this.CheckedRows = data;
      }
    );
  }
  cleared() {
    this.SharedMethodService.cleared(
      this.checkedIds,
      this.tableData,
      this.datatable
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
  } //清空选中行
  pageIndexChange($event: any) {
    this.filter();
  } //切换页码
  pageSizeChange($event: any) {
    this.filter();
  } //改变每页显示数量
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框

  // allLog() {
  //   this.JobOrderService.GetAllOutsourcingInspectionOrderLogs(
  //     1,
  //     9999
  //   ).subscribe((data: any) => {
  //     const logData = data.items;
  //     const columns = [
  //       {
  //         field: '生产质检单号',
  //         header: '生产质检单号',
  //         fieldType: 'text',
  //       },
  //       {
  //         field: 'content',
  //         header: '日志内容',
  //         fieldType: 'text',
  //       },
  //       {
  //         field: '执行人',
  //         header: '执行人',
  //         fieldType: 'text',
  //       },
  //       {
  //         field: '执行时间',
  //         header: '执行时间',
  //         fieldType: 'text',
  //       },
  //     ];
  //     this.results = this.drawerService.open({
  //       drawerContentComponent: LogComponent,
  //       width: '40%',
  //       data: { data: logData, columns: columns },
  //       zIndex: 1000,
  //       isCover: false,
  //       fullScreen: true,
  //       backdropCloseable: true,
  //       escKeyCloseable: true,
  //       position: 'right',
  //       resizable: true,
  //       onClose: () => {},
  //     });
  //   });
  // }
  // GetLogsById(id: any) {
  //   this.JobOrderService.GetLogsByOutsourcingInspectionOrderId(
  //     id,
  //     1,
  //     9999
  //   ).subscribe((data: any) => {
  //     const logData = data.items;
  //     const columns = [
  //       {
  //         field: '采购质检单号',
  //         header: '采购质检单号',
  //         fieldType: 'text',
  //       },
  //       {
  //         field: 'content',
  //         header: '日志内容',
  //         fieldType: 'text',
  //       },
  //       {
  //         field: '执行人',
  //         header: '执行人',
  //         fieldType: 'text',
  //       },
  //       {
  //         field: '执行时间',
  //         header: '执行时间',
  //         fieldType: 'text',
  //       },
  //     ];
  //     this.results = this.drawerService.open({
  //       drawerContentComponent: LogComponent,
  //       width: '40%',
  //       data: { data: logData, columns: columns },
  //       zIndex: 1000,
  //       isCover: false,
  //       fullScreen: true,
  //       backdropCloseable: true,
  //       escKeyCloseable: true,
  //       position: 'right',
  //       resizable: true,
  //       onClose: () => {},
  //     });
  //   });
  // }
  checkCustomerIDs(customerRows: any) {
    // 如果数组长度为1或为空，直接返回true
    if (customerRows.length <= 1) {
      return true;
    }
    // 获取第一个元素的customerID
    const firstCustomerID = customerRows[0].customerID;
    // 检查数组中每个元素的customerID是否都与第一个元素的customerID相同
    return customerRows.every(
      (row: { customerID: any }) => row.customerID === firstCustomerID
    );
  }
  fujian(rowitem: any, dialogtype?: string) {
    const results = this.dialogService.open({
      title: '附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '销售附件',
        urls: rowitem.files,
        type: '查看',
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  showDetail(data: any, rowIndex: any) {
    this.selectedRowIndex = rowIndex;
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + url);
    return urls;
  }
  // dateChange() {
  //   this.fifter.StartTime = this.date[0]
  //     .toLocaleDateString('zh-CN', {
  //       year: 'numeric',
  //       month: '2-digit',
  //       day: '2-digit',
  //     })
  //     .replace(/\//g, '/');
  //   this.fifter.EndTime = this.date[1]
  //     .toLocaleDateString('zh-CN', {
  //       year: 'numeric',
  //       month: '2-digit',
  //       day: '2-digit',
  //     })
  //     .replace(/\//g, '/');
  // }

  checkedCodes = [];
  clickCode(rowItem: any, type: string, dialogtype?: string) {
    {
      let data = {
        data: rowItem,
        type: type,
        disPlay: false,
      };
      const results = this.DialogService.open({
        id: 'custom',
        width: '80vw',
        maxHeight: '90vh',
        backdropCloseable: true,
        content: ProductInspectionDetailsComponent,
        dialogtype: dialogtype,
        data: data,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              if (
                results.modalContentInstance.tempData.data.qualifiedQuantity !==
                null
              ) {
                  this.JobOrderService.PerformProductionInspection(
                    {
                      productionInspectionOrderId: rowItem.productionInspectionOrderId,
                      inspectionStatus: results.modalContentInstance.tempData.data.inspectionResult,
                      qualifiedAmount: results.modalContentInstance.tempData.data.qualifiedAmount,
                      unqualifiedAmount: results.modalContentInstance.tempData.data.unqualifiedAmount,
                      scrapAmount: results.modalContentInstance.tempData.data.scrapAmount,
                      remarks: results.modalContentInstance.tempData.data.remarks,
                      attachments: [
                      ],
                      inspectorEmployeeCode:this.employeeCode
                    }
                  ).subscribe(
                    (res) => {
                      this.showToast('success', '成功', '检验成功');
                      this.filter();
                      results.modalInstance.hide();
                    },
                    (error) => {
                      this.showToast(
                        'error',
                        '错误',
                        error.error || '服务器连接失败'
                      );
                    }
                  );
              } else if (
                results.modalContentInstance.tempData.data.qualifiedQuantity ==
                null
              ) {
                this.showToast('error', '错误', '请输入数量');
              }
            },
          },
          // {
          //   id: 'btn-cancel',
          //   cssClass: 'common',
          //   text: '暂存',
          //   handler: ($event: Event) => {
          //     // if (
          //     //   results.modalContentInstance.tempData.data.qualifiedQuantity !==
          //     //   null
          //     // ) {
          //     //   this.JobOrderService.CreateOrUpdateInspectionOrderTemporary({
          //     //     inspectionOrderTemporaryId: null,
          //     //     inspectionOrderId:
          //     //       results.modalContentInstance.tempData.data
          //     //         .purchaseInspectionOrderId,
          //     //     inspectionOrderNum:
          //     //       results.modalContentInstance.tempData.data
          //     //         .purchaseInspectionOrderNum,
          //     //     qualifiedQuantity:
          //     //       results.modalContentInstance.tempData.data
          //     //         .qualifiedQuantity,
          //     //     unqualifiedQuantity:
          //     //       results.modalContentInstance.tempData.data
          //     //         .unqualifiedQuantity,
          //     //   }).subscribe(
          //     //     (res) => {
          //     //       this.showToast('success', '成功', '暂存成功');
          //     //       this.filter();
          //     //       results.modalInstance.hide();
          //     //     },
          //     //     (error) => {
          //     //       this.showToast(
          //     //         'error',
          //     //         '错误',
          //     //         error.error || '服务器连接失败'
          //     //       );
          //     //     }
          //     //   );
          //     // } else if (
          //     //   results.modalContentInstance.tempData.data.qualifiedQuantity ==
          //     //   null
          //     // ) {
          //     //   this.showToast('error', '错误', '请输入数量');
          //     // }
          //   },
          // },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }
  clickCode2(rowItem: any, type: string, dialogtype?: string) {
    {
      let data = {
        data: rowItem,
        type: type,
        disPlay: false,
      };
      const results = this.DialogService.open({
        id: 'custom',
        width: '80vw',
        maxHeight: '90vh',
        backdropCloseable: true,
        content: ProductInspectionDetailsComponent,
        dialogtype: dialogtype,
        data: data,
        onClose: () => {},
        buttons: [
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '关闭',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }
  getImagesArray2(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + '/' + url);
    return urls;
  }
  add(){
    this.router.navigate(['/pages/inspection/product-inspection/add']); // 替换为你的目标路由
  }
}
